#include "mainwidget.h"
#include "ui_mainwidget.h"
#include <common/common.h>
#include "common/gui/input/numberkeyboard.h"
#include <common/floatcompara.h>
#include "settings/comsettingwidget.h"
#include <QSerialPort>
#include "optiondialog.h"
#include "EditorWidgets/editwidget.h"
#include "database/dbtabuser.h"
#include "database/dbtabproduct.h"
#include "database/dbtabrecordhlo.h"
#include "database/dbtabrecordclass.h"
#include "dataview/productmodel.h"
#include "dataview/classifierproductmodel.h"
#include "database/dbtabclassifierproduct.h"
#include "dataview/classifierproductmodel.h"
#include "EditorWidgets/classifierselector.h"
#include "EditorWidgets/classifierprteditor.h"
#include "check_output.h"
#include "settings/parametersettings.h"
#include "myserialport/myserialport.h"
#include <QUuid>
#include <array>
#include "checkvaluewidget.h"
#include "settings/IOSettings/output.h"
#include "communication/tcpclient.h"
#include "LINUXTCP/modbus.h"
#include "mbreghandler.h"


MainWidget* MainWidget::mMainWidget = NULL;

#if QT_VERSION < 0X050000
extern QWSInputMethod* gInputMethod;
#endif
MainWidget::MainWidget(QWidget *parent) :
    QWidget(parent),mHi(0),mLo(0),mOk(0),mHaveChecked(false),getStabNet(false),mChkResult(CHECK_NONE),mRecordNo(0)
    ,mBrand(""),mBarcode(""),mStabCnt(0),mCanUpdateScale(true),mSwitch(false),
    ui(new Ui::MainWidget)
{
    ui->setupUi(this);    
    this->setWindowFlags(Qt::FramelessWindowHint);
    this->setWindowState(Qt::WindowMaximized);   

    QTimer *syncTimer = new QTimer(this);
    syncTimer->setSingleShot(true);
    syncTimer->start(1000);
    connect(syncTimer,SIGNAL(timeout()),this,SLOT(syncPa()));
    //this->setFixedSize();
    TcpClient::getInstanse();
    StartModbus( MBRegHandler::getHandler(this));
    initUseMode();
    initMainValueWidget();
    mExportTool = new ExportTool(this);
    //ui->weightWidget->setColor(Qt::red,(uint)(0x0));
    QTimer *paraTimer = new QTimer(this);
    paraTimer->setSingleShot(true);
    paraTimer->start(3000);
    connect(paraTimer,SIGNAL(timeout()),this,SLOT(updateScalePara()));
    onUpdateTare(SPSCALEADAPTOR()->stringTare());

#if QT_VERSION < 0X050000
    gInputMethod = SyszuxIM::createSyszuxIM(this);
    QWSServer::setCurrentInputMethod(gInputMethod);
#endif
    //SPSCALEADAPTOR()->syncScalePara();
    connect(SPSCALEADAPTOR(),SIGNAL(getTare(QString)),this,SLOT(onUpdateTare(QString)));
    mUseMode = (UseMode)ParameterSettings::getUseMode();
    mCheckMode = (CheckMode)ParameterSettings::getCheckMode();
    mAutoUsbCopy = ParameterSettings::getAutoUsbCopySw();

//    ui->tw_set->horizontalHeader()->setStyleSheet("QHeaderView::section {background-color: rgb(134, 187, 237);"
//                                                  "color: white;padding-left: 8px;border: 1px solid #6c6c6c;}");
//    ui->tw_statics->horizontalHeader()->setStyleSheet("QHeaderView::section {background-color: rgb(134, 187, 237);"
//                                                      "color: white;padding-left: 8px;border: 1px solid #6c6c6c;}");
//    ui->tw_set->setEditTriggers(QAbstractItemView::NoEditTriggers);
//    ui->tw_set->setSelectionMode(QAbstractItemView::NoSelection);
//    ui->tw_statics->setEditTriggers(QAbstractItemView::NoEditTriggers);
//    ui->tw_statics->setSelectionMode(QAbstractItemView::NoSelection);

//    ui->tw_set->horizontalHeaderItem(0)->setSizeHint(QSize(0,40));
//    ui->tw_statics->horizontalHeaderItem(0)->setSizeHint(QSize(0,40));

//    for(int i=0;i<4;i++)
//    {
//        ui->tw_set->horizontalHeaderItem(i)->setFont(QFont("Ubuntu",16));
//        ui->tw_statics->horizontalHeaderItem(i)->setFont(QFont("Ubuntu",16));
//    }
    login(QModelIndex());
    //SPSCALEADAPTOR()->syncScalePara();
    connect(SPSCALEADAPTOR(),SIGNAL(updateScale()),this,SLOT(onUpdateScale()));
    connect(ui->w_check,SIGNAL(valueInput(int)),this,SLOT(toInputCheckValue(int)));

    connect(inMgr,SIGNAL(in(bool)),this,SLOT(slot_testin(bool)));
    connect(inMgr,SIGNAL(out(bool)),this,SLOT(slot_testout(bool)));
    connect(inMgr,SIGNAL(positon1(bool)),this,SLOT(slot_test1(bool)));
    connect(inMgr,SIGNAL(positon2(bool)),this,SLOT(slot_test2(bool)));
    qApp->installEventFilter(this);
//    installEventFilter(ui->lab_fontSpd);
//    installEventFilter(ui->lab_weighingSpd);
//    installEventFilter(ui->lab_backSpd);
}

bool MainWidget::eventFilter(QObject *obj, QEvent *event)
{
    QEvent::Type type = event->type();
    if(type == QEvent::MouseButtonPress)
    {qDebug()<<"press";
        if(obj->inherits("QAbstractButton")||obj->objectName()=="qt_scrollarea_viewport")
        {
            beep1;
        }
        if(obj == ui->lab_fontSpd)
        {
            NumberKeyboard *key = new NumberKeyboard(6,0,0);
            connect(key,SIGNAL(quitWithText(QString)),this,SLOT(onAcceptFontSpeed(QString)));
            key->exec();
        }
        else if(obj == ui->lab_weighingSpd)
        {
            NumberKeyboard *key = new NumberKeyboard(6,0,0);
            connect(key,SIGNAL(quitWithText(QString)),this,SLOT(onAcceptWeighingSpeed(QString)));
            key->exec();
        }
        else if(obj == ui->lab_backSpd)
        {
            NumberKeyboard *key = new NumberKeyboard(6,0,0);
            connect(key,SIGNAL(quitWithText(QString)),this,SLOT(onAcceptBackSpeed(QString)));
            key->exec();
        }
    }
    return QWidget::eventFilter(obj,event);
}

void MainWidget::onUpdateScale()
{qDebug()<<this->isVisible();
    if(!this->isActiveWindow()||!mCanUpdateScale) return;//不在主界面
    float net = SPSCALEADAPTOR()->floatNet();
    updateStabFlag();
    updateZeroFlag();
    if(F_BZ(net-SPSCALEADAPTOR()->getMax()))
    {
        ui->weightWidget->setMainStr("OL");
        ui->lab_isOL->setStyleSheet("color:#43EB1F;");
        return;
    }
    else
    {
        ui->weightWidget->setMainStr(SPSCALEADAPTOR()->stringNet());
        ui->lab_isOL->setStyleSheet("color:white;");
    }


    checkWeight(net);

    if(SPSCALEADAPTOR()->zeroFlag())//小于最小称重
    {   //qDebug()<<"zero";
        getStabNet = false;
        return;
    }
    else if(!SPSCALEADAPTOR()->stabFlag()){
        mStabCnt = 0;
    }
    else if(/*mStabCnt++ > 1&&*/!getStabNet)
    {//qDebug()<<net;
        mLastStabNet = net;
        getStabNet = true;
        saveRecord();
    }
}

void MainWidget::onUpdateTare(const QString& tare)
{qDebug()<<tare;
    ui->weightWidget->setleftBottomStr("T="+tare+SPSCALEADAPTOR()->getUnit());
}

void MainWidget::onHasLogin()
{
    mCanUpdateScale = true;
}

MainWidget::~MainWidget()
{
    delete ui;
}

MainWidget *MainWidget::getObj()
{
    if(mMainWidget==NULL)
    {
        mMainWidget = new MainWidget();
    }
    return mMainWidget;
}

void MainWidget::changeUser(const QString &str)
{
    //ui->btn_user->setText(QString("用户[%1]").arg(str));
    ui->lab_user->setText(str);
    mUser = str;
}

void MainWidget::initUseMode()//此函数在parametersettings类里有调用
{
    mUseMode = (UseMode)ParameterSettings::getUseMode();qDebug()<<"usmode"<<mUseMode;
    mProduct = "";mBarcode = "";mHi = 0;mOk = 0;mLo = 0;
    CheckValueContainer* chkValues = new CheckValueContainer(this);
    mChkValuesMap.insert("nullproduct",chkValues);//一个品名对应一个CheckValueContainer
    if(mUseMode == ELIMINATE)
    {
        ui->w_classifier->hide();
        //ui->tw_set->hide();
        //ui->tw_statics->hide();
        ui->w_check->show();
        ui->w_classifier->clearAll();
    }
    else {
        //ui->tw_set->hide();
        //ui->tw_statics->hide();
        ui->w_check->hide();
        ui->w_classifier->show();
        ui->w_check->clearAll();
    }
}

void MainWidget::initCheckMode()
{
    mCheckMode = (CheckMode)ParameterSettings::getCheckMode();
}

void MainWidget::setHi(float hi)
{
    if(mUseMode == ELIMINATE)
    {
        if(QString::compare(mProduct,"nullproduct")!=0)
        {
            clearEliminate();
            mProduct = "nullproduct";
            CheckValueContainer* container = new CheckValueContainer(this);
            mChkValuesMap.insert(mProduct,container);
        }
        mHi = hi;
        ui->w_check->setHiValue(QString::number(mHi));
        checkWeight(SPSCALEADAPTOR()->floatNet());
    }
}

void MainWidget::setLow(float low)
{
    if(mUseMode == ELIMINATE)
    {
        if(QString::compare(mProduct,"nullproduct")!=0)
        {
            clearEliminate();
            mProduct = "nullproduct";
            CheckValueContainer* container = new CheckValueContainer(this);
            mChkValuesMap.insert(mProduct,container);
        }
        mLo = low;
        ui->w_check->setLoValue(QString::number(mLo));
        checkWeight(SPSCALEADAPTOR()->floatNet());
    }
}

void MainWidget::slot_testin(bool status)
{
    qDebug()<<"in "<<status;
}

void MainWidget::slot_testout(bool status)
{
    qDebug()<<"out "<<status;
}

void MainWidget::slot_test1(bool status)
{
    qDebug()<<"p1 "<<status;
}

void MainWidget::slot_test2(bool status)
{
    qDebug()<<"p2 "<<status;
}

void MainWidget::updateScalePara()
{qDebug()<<"updateScalePara";
    ui->weightWidget->setUnitStr(SPSCALEADAPTOR()->getUnit());
    ui->weightWidget->setLeftTopStr("Max="+ SPSCALEADAPTOR()->getMaxStr()+SPSCALEADAPTOR()->getUnit()
                                    + " D="+QString::number(SPSCALEADAPTOR()->getDivi()));
    ui->weightWidget->setleftBottomStr("T="+SPSCALEADAPTOR()->stringTare()+SPSCALEADAPTOR()->getUnit());
}

void MainWidget::tareScale(float w)
{
    SPSCALEADAPTOR()->tareScale(w);
}

void MainWidget::preTareScale(float weight)
{
    SPSCALEADAPTOR()->tareScale(weight);
}

void MainWidget::zeroScale()
{
    SPSCALEADAPTOR()->zeroScale();
    onUpdateTare(SPSCALEADAPTOR()->stringTare());
}

void MainWidget::syncPa()
{
    SPSCALEADAPTOR()->syncScalePara();
}

void MainWidget::checkWeight(float net)
{
    if(mUseMode == ELIMINATE)
    {
        checkLOH(net);
    }
    else
    {
        checkClass(net);
    }
}

void MainWidget::checkLOH(float net)
{
    ChkResult chkrslt = CHECK_END;
    if(SPSCALEADAPTOR()->zeroFlag()||(F_SEZ(mHi)&&F_SEZ(mLo)))//零区或者上下限都为0,将检重结果置为CHECK_NONE
    {
        chkrslt = CHECK_NONE;
        mHaveChecked = false;
        updateCheckStatus(false);//显示标志“检完”
        //qDebug()<<"check none";
        if(mChkResult != chkrslt)
        {
            mChkResult = chkrslt;qDebug()<<mChkResult;
            changeChkColor();
            setCheckOutput();
        }
    }
    else if(!mHaveChecked&&SPSCALEADAPTOR()->stabFlag())//稳定了并且没有检重过
    {
        CheckValueContainer* chkVaCo;qDebug()<<"check stable";
        if(!mProduct.isEmpty()) chkVaCo = mChkValuesMap[mProduct];qDebug();
        mHaveChecked = true;
        if(net<mLo)
        {
            chkrslt = CHECK_LOW;
            chkVaCo->calLoValues(net);
        }
        else if(net<=mHi){
            chkrslt = CHECK_OK;
            chkVaCo->calOkValues(net);
        }
        else if(net>mHi){
            chkrslt = CHECK_HIGH;
            chkVaCo->calHiValues(net);
        }
        updateCheckStatus(true);//显示标志“检完”
        if(mChkResult != chkrslt)
        {
            mChkResult = chkrslt;//qDebug()<<mChkResult;
            changeChkColor();
            setCheckOutput();
        }
    }
}

void MainWidget::changeChkColor()
{//qDebug()<<mChkResult;
    switch(mChkResult)
    {
    default:
    case CHECK_NONE:
         ui->weightWidget->setColor(0x201F3B,(uint)(0xffffff));
        break;
    case CHECK_LOW:
         ui->weightWidget->setColor(0xff9903,(uint)(0x0));
        break;
    case CHECK_OK:
         ui->weightWidget->setColor(Qt::green,(uint)(0x0));
        break;
    case CHECK_HIGH:
         ui->weightWidget->setColor(Qt::red,(uint)(0x0));
        break;
    }
}

void MainWidget::setCheckOutput()
{
    //if(!mSwitch) return;
    switch(mChkResult)
    {
    default:
    case CHECK_NONE:
        dis_all();
        dis_buzz();
        //_stop();
        break;
    case CHECK_LOW:
        en_lo();
        //_start();
        en_buzz();
        break;
    case CHECK_OK:
        en_ok();
        //_start();
        break;
    case CHECK_HIGH:
        en_hi();
        //_start();
        en_buzz();
        break;
    }//高和低才鸣叫
}

void MainWidget::checkClass(float net)
{
    //ClassResult chkrslt = CLASS_END;
    mClassResult = CLASS_END;
    if(SPSCALEADAPTOR()->zeroFlag()||mProduct.isEmpty())//零区或者上下限都为0,将检重结果置为CHECK_NONE
    {
        mClassResult = CLASS_NONE;
        mHaveChecked = false;
        updateCheckStatus(false);
        qDebug()<<"zero-NONE";
    }
    else if(!mHaveChecked&&SPSCALEADAPTOR()->stabFlag())
    {
        mClassResult = CLASS_NONE;
        mHaveChecked = true;
        for(auto i = mRmap.begin();i!=mRmap.end();i++)
        {
            if(net>=i.value().lo&&net<=i.value().hi)
            {
                mClassResult = (ClassResult)i.key();qDebug()<<__LINE__;
                if(mClassValuesMap.contains(mProduct)) mClassValuesMap[mProduct]->calValues(mClassResult,net);
                break;
            }
        }
        updateCheckStatus(true);
    }
    if(mClassResult!=CLASS_END) en_range(mClassResult);
}

void MainWidget::saveRecord()
{
    if(!mProduct.isEmpty())
    {
        beep1;
        recordSaveToDB();
    }
}

void MainWidget::recordSaveToDB()
{
    if(mUseMode == ELIMINATE)
    {
        saveToRecordHLO();
        if(mChkResult!=CHECK_NONE)
            updateCheckWidget();
    }
    else {
        saveToRecordClass();
        updateClassWidget();
    }
}

void MainWidget::saveToRecordHLO()
{qDebug()<<mRecordNo;
    mRecordNo++;
    DataBaseQuery query;
    QMap<QString,QVariant> map;
    map.insert(DBTabRecordHLO::_UUID,QUuid::createUuid().toString());
    map.insert(DBTabRecordHLO::_DATE,QDate::currentDate().toString("yy-MM-dd"));
    map.insert(DBTabRecordHLO::_TIME,QTime::currentTime().toString("hh:mm:ss"));
    map.insert(DBTabRecordHLO::_RECORD_NO,mRecordNo);
    map.insert(DBTabRecordHLO::_PRODUCT_NAME,mProduct);
    map.insert(DBTabRecordHLO::_PRODUCT_BRAND,mBrand);
    map.insert(DBTabRecordHLO::_BARCODE,mBarcode);
    map.insert(DBTabRecordHLO::_NET,mLastStabNet);
    map.insert(DBTabRecordHLO::_TARE,SPSCALEADAPTOR()->stringTare());
    map.insert(DBTabRecordHLO::_GROSS,SPSCALEADAPTOR()->stringGross());
    map.insert(DBTabRecordHLO::_HI,mHi);
    map.insert(DBTabRecordHLO::_OK,mOk);
    map.insert(DBTabRecordHLO::_LOW,mLo);
    map.insert(DBTabRecordHLO::_CHKRESULT,mChkResult);
    map.insert(DBTabRecordHLO::_USER,LoginDialog::user());
    query.insert(DBTabRecordHLO::TAB_NAME,map);
    if(!mAutoUsbCopy)
    {
        return;
    }
    QByteArray lineArr = "";
    lineArr.append(map[DBTabRecordHLO::_DATE].toByteArray());
    lineArr.append(",");
    lineArr.append(map[DBTabRecordHLO::_TIME].toByteArray());
    lineArr.append(",");
    lineArr.append(map[DBTabRecordHLO::_PRODUCT_NAME].toByteArray());
    lineArr.append(",");
    lineArr.append(map[DBTabRecordHLO::_NET].toByteArray());
    lineArr.append(",");
    lineArr.append(map[DBTabRecordHLO::_TARE].toByteArray());
    lineArr.append(",");
    lineArr.append(map[DBTabRecordHLO::_GROSS].toByteArray());
    lineArr.append(",");
    lineArr.append(map[DBTabRecordHLO::_HI].toByteArray());
    lineArr.append(",");
    lineArr.append(map[DBTabRecordHLO::_OK].toByteArray());
    lineArr.append(",");
    lineArr.append(map[DBTabRecordHLO::_LOW].toByteArray());
    lineArr.append(",");
    lineArr.append(map[DBTabRecordHLO::_CHKRESULT].toByteArray());
    lineArr.append(",");
    lineArr.append(map[DBTabRecordHLO::_USER].toByteArray());
    lineArr.append("\r\n");
    mExportTool->writeLineToFile(lineArr,"CheckRecord"+QDate::currentDate().toString("yyyyMMdd")+".csv",mUseMode);
}

void MainWidget::saveToRecordClass()
{
    mRecordNo++;
    DataBaseQuery query;
    QMap<QString,QVariant> map;
    map.insert(DBTabRecordClass::_UUID,QUuid::createUuid().toString());
    map.insert(DBTabRecordClass::_DATE,QDate::currentDate().toString("yy-MM-dd"));
    map.insert(DBTabRecordClass::_TIME,QTime::currentTime().toString("hh:mm:ss"));
    map.insert(DBTabRecordClass::_RECORD_NO,mRecordNo);
    map.insert(DBTabRecordClass::_PRODUCT_NAME,mProduct);
    map.insert(DBTabRecordClass::_PRODUCT_BRAND,mBrand);
    map.insert(DBTabRecordClass::_BARCODE,mBarcode);
    map.insert(DBTabRecordClass::_NET,mLastStabNet);
    map.insert(DBTabRecordClass::_TARE,SPSCALEADAPTOR()->stringTare());
    map.insert(DBTabRecordClass::_GROSS,SPSCALEADAPTOR()->stringGross());
    map.insert(DBTabRecordClass::_RANGE,mRmap[mClassResult].str());
    map.insert(DBTabRecordClass::_CHKRESULT,mClassResult);
    map.insert(DBTabRecordClass::_USER,LoginDialog::user());
    query.insert(DBTabRecordClass::TAB_NAME,map);

    if(!mAutoUsbCopy)
    {
        return;
    }
    QByteArray lineArr = "";
    lineArr.append(map[DBTabRecordClass::_DATE].toByteArray());
    lineArr.append(",");
    lineArr.append(map[DBTabRecordClass::_TIME].toByteArray());
    lineArr.append(",");
    lineArr.append(map[DBTabRecordClass::_PRODUCT_NAME].toByteArray());
    lineArr.append(",");
    lineArr.append(map[DBTabRecordClass::_NET].toByteArray());
    lineArr.append(",");
    lineArr.append(map[DBTabRecordClass::_TARE].toByteArray());
    lineArr.append(",");
    lineArr.append(map[DBTabRecordClass::_GROSS].toByteArray());
    lineArr.append(",");
    lineArr.append(map[DBTabRecordClass::_RANGE].toByteArray());
    lineArr.append(",");
    lineArr.append(map[DBTabRecordClass::_CHKRESULT].toByteArray());
    lineArr.append(",");
    lineArr.append(map[DBTabRecordClass::_USER].toByteArray());
    lineArr.append("\r\n");
    mExportTool->writeLineToFile(lineArr,"ClassifierRecord"+QDate::currentDate().toString("yyyyMMdd")+".csv",mUseMode);
}

void MainWidget::updateCheckWidget()//更新检重数据到界面
{
    switch (mChkResult) {
    case CHECK_LOW:
        ui->w_check->setLoValues(QString("%1/%2").arg(mChkValuesMap[mProduct]->mToLoWgt).arg(mChkValuesMap[mProduct]->mToLoCnt)
                                 ,QString::number(mChkValuesMap[mProduct]->mLoMax),QString::number(mChkValuesMap[mProduct]->mLoMin)
                                 ,QString::number(mChkValuesMap[mProduct]->mLoAve));
        break;
    case CHECK_OK:
        ui->w_check->setOkValues(QString("%1/%2").arg(mChkValuesMap[mProduct]->mToOkWgt).arg(mChkValuesMap[mProduct]->mToOkCnt)
                                 ,QString::number(mChkValuesMap[mProduct]->mOkMax),QString::number(mChkValuesMap[mProduct]->mOkMin)
                                 ,QString::number(mChkValuesMap[mProduct]->mOkAve));
        break;
    case CHECK_HIGH:
        ui->w_check->setHiValues(QString("%1/%2").arg(mChkValuesMap[mProduct]->mToHiWgt).arg(mChkValuesMap[mProduct]->mToHiCnt)
                                 ,QString::number(mChkValuesMap[mProduct]->mHiMax),QString::number(mChkValuesMap[mProduct]->mHiMin)
                                 ,QString::number(mChkValuesMap[mProduct]->mHiAve));
        break;
    default:
        break;
    }
}

void MainWidget::updateClassWidget()//更新分选数据到界面
{
    if(mClassResult>CLASS_NONE&&mClassResult<CLASS_END)
    {
        if(mClassValuesMap.contains(mProduct))
        {
            float toWgt = mClassValuesMap[mProduct]->mToWgt[mClassResult-1];
            int toCnt = mClassValuesMap[mProduct]->mToCnt[mClassResult-1];
            ui->w_classifier->setToWgtAndCnt(mClassResult-1,QString("%1/%2").arg(toWgt).arg(toCnt));
        }
    }
}

void MainWidget::updateStabFlag()
{
    static bool isStab = true;
    if(SPSCALEADAPTOR()->stabFlag()==isStab)
        return;
    else
    {
        isStab = SPSCALEADAPTOR()->stabFlag();
    }
    if(isStab)
        ui->lab_isStab->setStyleSheet("color:#43EB1F;");
    else
        ui->lab_isStab->setStyleSheet("color:white;");
}

void MainWidget::updateZeroFlag()
{
    static bool isZero = true;
    if(SPSCALEADAPTOR()->zeroFlag()==isZero)
        return;
    else
    {
        isZero = SPSCALEADAPTOR()->zeroFlag();
    }
    if(isZero)
        ui->lab_isZero->setStyleSheet("color:#43EB1F;");//green
    else
        ui->lab_isZero->setStyleSheet("color:white;");
}

void MainWidget::updateCheckStatus(bool isOver)
{
    if(isOver)
        ui->lab_checkOver->setStyleSheet("color:#43EB1F;");
    else
        ui->lab_checkOver->setStyleSheet("color:white;");
}

void MainWidget::clearEliminate()
{
    ui->w_check->clearAll();
    if(mChkValuesMap.contains(mProduct))
    {
        CheckValueContainer* container = mChkValuesMap[mProduct];
        mChkValuesMap.remove(mProduct);
        delete container;
    }
    mProduct = "";
    mHi=0;mLo=0;mOk=0;
}

void MainWidget::clearClass()
{
    ui->w_classifier->clearAll();
    if(mClassValuesMap.contains(mProduct))
    {
        ClassValueContainer* container = mClassValuesMap[mProduct];
        mClassValuesMap.remove(mProduct);
        delete container;
    }
    mProduct = "";
    mBarcode = "";
}

void MainWidget::initMainValueWidget()
{
    ui->weightWidget->setColor(0x201F3B,Qt::white/*QColor(255,255,255)*//*(uint)(0xffffff)*/);
    ui->weightWidget->setMainFont(QFont("DejaVu Sans",80,60));//DejaVu Sans//Ubuntu Bold
    ui->weightWidget->setleftBottomStr("");
    //ui->weightWidget->setLeftTopStr("Max:"+ SPSCALEADAPTOR()->getMaxStr());
    ui->weightWidget->setLeftTopStr("Max="+ SPSCALEADAPTOR()->getMaxStr()
                                    + " d="+QString::number(SPSCALEADAPTOR()->getDivi()));
}

void MainWidget::login(const QModelIndex &index)
{
//    UserModel *model = new UserModel();
//    if(model->dataCount()!=0 )
//    {
        QWidget  * back = new QWidget(this);
        back->setGeometry(WINDOW_GEOMETRY(1,1));
        back->setStyleSheet("background-color: rgba(0, 0, 0,200);");
        back->show();
        //mPermission = UserModel::OPERATOR;
        lg = new LoginDialog(index,back);
        lg->show();
        mCanUpdateScale = false;
        connect(lg,SIGNAL(hasLogin()),this,SLOT(onHasLogin()));
//        connect(this,SIGNAL(getUserFromCardReader()),lg,SLOT(accept()));
        connect(lg,SIGNAL(destroyed()),back,SLOT(deleteLater()));
//        if(OperateSettingWidget::getCalRemind()){
//            connect(lg,SIGNAL(destroyed()),this,SLOT(calibrate()));
//        }
//        changeUser(LoginDialog::technicianString());
        //StatusBar::getStatusBar()->changeOperator(LoginDialog::technicianString());
}

void MainWidget::changeProduct(const QModelIndex &index)
{
    QString product = index.data(ProductModel::ROLE_NAME).toString();
    if(mProduct != product)
    {
        ui->w_check->clearAll();//切换产品，界面数据清空
        mProduct = product;
    }
    mHi = index.data(ProductModel::ROLE_HI).toFloat();qDebug()<<mHi;
    mOk = index.data(ProductModel::ROLE_OK).toFloat();qDebug()<<mOk;
    mLo = index.data(ProductModel::ROLE_LOW).toFloat();qDebug()<<mLo;
    ui->w_check->setProductName(mProduct);
    ui->w_check->setHiValue(QString::number(mHi));
    ui->w_check->setOkValue(QString::number(mOk));
    ui->w_check->setLoValue(QString::number(mLo));
    qDebug()<<mChkValuesMap.keys();
    if(!mChkValuesMap.contains(mProduct))
    {
        CheckValueContainer* chkValues = new CheckValueContainer(this);
        mChkValuesMap.insert(mProduct,chkValues);//一个品名对应一个CheckValueContainer
    }
    else
    {
        ui->w_check->setLoValues(QString("%1/%2").arg(mChkValuesMap[mProduct]->mToLoWgt).arg(mChkValuesMap[mProduct]->mToLoCnt)
                                 ,QString::number(mChkValuesMap[mProduct]->mLoMax),QString::number(mChkValuesMap[mProduct]->mLoMin)
                                 ,QString::number(mChkValuesMap[mProduct]->mLoAve));
        ui->w_check->setOkValues(QString("%1/%2").arg(mChkValuesMap[mProduct]->mToOkWgt).arg(mChkValuesMap[mProduct]->mToOkCnt)
                                 ,QString::number(mChkValuesMap[mProduct]->mOkMax),QString::number(mChkValuesMap[mProduct]->mOkMin)
                                 ,QString::number(mChkValuesMap[mProduct]->mOkAve));
        ui->w_check->setHiValues(QString("%1/%2").arg(mChkValuesMap[mProduct]->mToHiWgt).arg(mChkValuesMap[mProduct]->mToHiCnt)
                                 ,QString::number(mChkValuesMap[mProduct]->mHiMax),QString::number(mChkValuesMap[mProduct]->mHiMin)
                                 ,QString::number(mChkValuesMap[mProduct]->mHiAve));
    }

//    ui->tw_set->item(0,0)->setText(mProduct);qDebug()<<"change";
//    ui->tw_set->item(0,1)->setText(QString::number(mHi));qDebug()<<"change";
//    ui->tw_set->item(0,2)->setText(QString::number(mOk));qDebug()<<"change";
//    ui->tw_set->item(0,3)->setText(QString::number(mLo));qDebug()<<"change";
}

void MainWidget::changeClassProduct(const QModelIndex &index)
{
    mProduct = index.data(ClassifierProductModel::ROLE_NAME).toString();
    mBarcode = index.data(ClassifierProductModel::ROLE_BARCODE).toString();
    //QList<Output::Range> rList;
    //mRlist.clear();
    mRmap.clear();
    for(int i = ClassifierProductModel::ROLE_R1_LOW;i<=ClassifierProductModel::ROLE_R12_LOW;i+=2)
    {
        Output::Range range;
        float lo = index.data(i).toFloat();
        float hi = index.data(i+1).toFloat();
        range.lo = lo;
        range.hi = hi;
        ui->w_classifier->setValue((i-ClassifierProductModel::ROLE_R1_LOW)/2
                                   ,QString("[%1-%2]").arg(lo).arg(hi));//显示范围值
        //mRlist << range;
        if(F_BZ(hi)||F_BZ(lo))
            mRmap.insert((i-ClassifierProductModel::ROLE_R1_LOW)/2+1,range);
    }qDebug()<<mRmap.keys();
    if(!mClassValuesMap.contains(mProduct))
    {
        ClassValueContainer* container = new ClassValueContainer(this);
        mClassValuesMap.insert(mProduct,container);
    }
    for(int i = 0;i<12;++i)
    {
        float toWgt = mClassValuesMap[mProduct]->mToWgt[i];
        int toCnt = mClassValuesMap[mProduct]->mToCnt[i];
        ui->w_classifier->setToWgtAndCnt(i,QString("%1/%2").arg(toWgt).arg(toCnt));
    }

//    foreach (auto out, outMgr->getOutputList()) {
//        int oprate = out->getOperation();
//        if(oprate>=OutputFunction::R1&&oprate<=OutputFunction::R12)
//        {
//            outMgr->saveOutputRange(out->getNo(),mRlist.at(oprate-OutputFunction::R1));
//        }
//    }
}

void MainWidget::on_btn_com_clicked()
{
//    comsettingwidget * widget = new comsettingwidget(this);
//    widget->show();
//    EditWidget* pwidget = new EditWidget(0,ui->verticalLayout_4,DBTabProduct::_NAME,EditWidget::PRODUCTMODEL);
//    connect(pwidget,SIGNAL(selectedItem(QModelIndex)),this,SLOT(changeProduct(QModelIndex)));
//    pwidget->show();
       EditWidget* pwidget;
      if(mUseMode==CLASSIFIER)
      {
        pwidget = new EditWidget(0,ui->verticalLayout_4,DBTabClassifierProduct::_NAME,EditWidget::CLASSIFIERPRTMODEL);
        connect(pwidget,SIGNAL(selectedItem(QModelIndex)),this,SLOT(changeClassProduct(QModelIndex)));
      }
      else{
        pwidget  = new EditWidget(0,ui->verticalLayout_4,DBTabProduct::_NAME,EditWidget::PRODUCTMODEL);
        connect(pwidget,SIGNAL(selectedItem(QModelIndex)),this,SLOT(changeProduct(QModelIndex)));
      }
      pwidget->show();
}

//void MainWidget::onReadyRead()
//{
//    QByteArray arr = mSp->readLine();
//    ui->label->clear();
//    ui->label->setText(QString(arr));
//}

//void MainWidget::initCom()
//{
//    mSp = new QSerialPort();
//    QString spName = "ttyS1";
//    mSp->setPortName(spName);
//    mSp->setBaudRate(QSerialPort::Baud115200);
//    mSp->setDataBits(QSerialPort::Data8);
//    mSp->setParity(QSerialPort::NoParity);
//    mSp->setFlowControl(QSerialPort::NoFlowControl);
//    mSp->setStopBits(QSerialPort::OneStop);
//    if(!mSp->open(QIODevice::ReadWrite))
//    {
//        return;
//    }
//    connect(mSp,SIGNAL(readyRead()),this,SLOT(onReadyRead()));
//}

//void MainWidget::on_btn_com_5_clicked()
//{
//#if QT_VERSION < 0X050000
//    int status =hal_get_lcd_status();
//    if(status==HAL_DISPLAY_BACKLIGHT_CLOSE)
//        hal_set_lcd_status(HAL_DISPLAY_BACKLIGHT_OPEN);
//    else
//        hal_set_lcd_status(HAL_DISPLAY_BACKLIGHT_CLOSE);
//#endif
//}

void MainWidget::on_btn_menu_clicked()
{
    //QApplication::beep();
    OptionDialog * dlg = new OptionDialog();
    connect(dlg,SIGNAL(destroyed()),this,SLOT(updateScalePara()));
    dlg->show();//
}

void MainWidget::on_btn_user_clicked()
{
    EditWidget* uwidget = new EditWidget(0,ui->verticalLayout_4,/*DBTabProduct::_NAME*/DBTabUser::_USER_NAME,/*EditWidget::PRODUCTMODEL*/EditWidget::USERMODEL);
    connect(uwidget,SIGNAL(selectedItem(QModelIndex)),this,SLOT(login(QModelIndex)));
    uwidget->show();
}

void MainWidget::on_btn_lock_clicked()
{
    login(QModelIndex());
}

void MainWidget::on_btn_start_clicked()
{
//    mSwitch = true;
    _start();
    ui->lab_isOn->setStyleSheet("color:#43EB1F;");
    ui->lab_isStop->setStyleSheet("color:white;");
}

void MainWidget::on_btn_stop_clicked()
{
//    mSwitch = false;
    _stop();
    ui->lab_isStop->setStyleSheet("color:#43EB1F;");
    ui->lab_isOn->setStyleSheet("color:white;");
}

void MainWidget::on_btn_clear_clicked()
{
    if(mUseMode == ELIMINATE)
    {
        clearEliminate();
    }
    else
    {
        clearClass();
    }
}

void MainWidget::on_btn_zero_clicked()
{
    zeroScale();
}

void MainWidget::on_btn_tare_clicked()
{
    float net = SPSCALEADAPTOR()->floatNet();

    if(F_EZ(net))
    {
        beep2;
    }
    else if(F_BZ(net))
    {qDebug()<<">0";
        tareScale(net);
    }
    else
    {qDebug()<<"<0";
        tareScale();
    }
}

void MainWidget::on_btn_preTare_clicked()
{
    NumberKeyboard* kb = new NumberKeyboard(5,2);
    kb->setWindowTitle("请输入预扣皮重");
    connect(kb,SIGNAL(quitWithText(QString)),this,SLOT(onAcceptPreTare(QString)));
    kb->exec();
}

void MainWidget::onAcceptPreTare(QString str)
{
    preTareScale(str.toFloat());
}

void MainWidget::onAcceptFontSpeed(QString str)//待实现
{
    ui->lab_fontSpd->setText(str);
}

void MainWidget::onAcceptWeighingSpeed(QString str)//待实现
{
    ui->lab_weighingSpd->setText(str);
}

void MainWidget::onAcceptBackSpeed(QString str)//待实现
{
    ui->lab_backSpd->setText(str);
}

void MainWidget::toInputCheckValue(int type)
{qDebug()<<"tpye"<<type;
    switch (type) {
    case 0:
    {
        NumberKeyboard* kb = new NumberKeyboard(5,SPSCALEADAPTOR()->getDeci());
        kb->setWindowTitle("请输入下限值");
        connect(kb,SIGNAL(quitWithText(QString)),this,SLOT(onAcceptLowVlue(QString)));
        kb->exec();
        break;
    }
    case 1:
    {
        NumberKeyboard* kb = new NumberKeyboard(5,SPSCALEADAPTOR()->getDeci());
        kb->setWindowTitle("请输入目标值");
        connect(kb,SIGNAL(quitWithText(QString)),this,SLOT(onAcceptOkVlue(QString)));
        kb->exec();
        break;
    }
    case 2:
    {
        NumberKeyboard* kb = new NumberKeyboard(5,SPSCALEADAPTOR()->getDeci());
        kb->setWindowTitle("请输入上限值");
        connect(kb,SIGNAL(quitWithText(QString)),this,SLOT(onAcceptHiVlue(QString)));
        kb->exec();
        break;
    }
    default:
        break;
    }
}

void MainWidget::onAcceptLowVlue(QString s)
{qDebug()<<"lowvalue";
    mLo = s.toFloat();
    if(QString::compare(mProduct,"nullproduct")!=0)
        mProduct = "nullproduct";
    ui->w_check->setLoValue(s);
}

void MainWidget::onAcceptOkVlue(QString s)
{
    mOk = s.toFloat();
    if(QString::compare(mProduct,"nullproduct")!=0)
        mProduct = "nullproduct";
    ui->w_check->setOkValue(s);
}

void MainWidget::onAcceptHiVlue(QString s)
{
    mHi = s.toFloat();
    if(QString::compare(mProduct,"nullproduct")!=0)
        mProduct = "nullproduct";
    ui->w_check->setHiValue(s);
}
